package com.example.nextstream.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.nextstream.annotations.AuthRequired;
import com.example.nextstream.dto.LoginSchema;
import com.example.nextstream.models.User;
import com.example.nextstream.service.UserService;
import com.example.nextstream.utils.RspBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/user")
public class UserApi {

    @Autowired
    private UserService userService;

    @RequestMapping("login")
    @ResponseBody
    @CrossOrigin
    public JSONObject login(@RequestParam("username") String username,
                            @RequestParam("password") String password){
        String token = userService.getToken(username,password);
        return RspBuilder.createSuccessRsp().append("username",username).append("token",token ).append("msg", 1).build();

    }

    @RequestMapping("listUsers")
    @AuthRequired
    @CrossOrigin
    public JSONObject listUsers(@RequestParam("pageSize") int pageSize,@RequestParam("pageNum") int pageNum) {

        Page<User> res = userService.listUser(pageNum,pageSize);
        return RspBuilder.createSuccessRsp().append("total",res.getTotal()).append("users",res.getRecords()).build();
    }

    @RequestMapping("createUser")
    @AuthRequired
    @CrossOrigin
    public JSONObject createUser(@RequestParam("username") String username,
                             @RequestParam("password") String password){
        User user= new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.createUser(user);
        return RspBuilder.createSuccessRsp().build();
    }
    @RequestMapping("count")
    @AuthRequired
    @CrossOrigin
    public JSONObject countUser(){
        Integer count =  userService.countUser();
        return RspBuilder.createSuccessRsp().append("count",count).build();
    }
    @RequestMapping("deleteUser")
    @AuthRequired
    @CrossOrigin
    public JSONObject deleteUser(@RequestParam("userId") Integer userId ){
        userService.deleteUser(userId);
        return RspBuilder.createSuccessRsp().build();
    }

    @RequestMapping("updatePassword")
    @AuthRequired
    @CrossOrigin
    public JSONObject updatePassword(@RequestParam("userId") Integer userId ,@RequestParam("newPass") String newPass ){
        User user = userService.getUserById(userId);
        user.setPassword(newPass);
        userService.updateUser(user);
        return RspBuilder.createSuccessRsp().build();
    }
}
